﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef SHARED_BASE_THREADPOOL_H_
#define SHARED_BASE_THREADPOOL_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <deque>
#include "Shared/Global_Macros.h"
#include "Shared/Base/Thread.h"
#include "Shared/Base/Mutex.h"


namespace Shared {
    class Runnable;
    class PooledThread;

    class ThreadPool
    {
    public:
        ThreadPool(int initThread, int maxThread, int priority = Thread::PRIO_NORMAL);
        ~ThreadPool(void);

        bool start(void);
        void stop(void);
        void join(void);

        bool start(Runnable *runnable);
        bool start(Runnable *runnable, int priority);
		bool start(Runnable **runables, int nRunnables);

        bool addCapacity(int threads);

    private:
        friend class PooledThread;
        typedef std::deque<PooledThread*> PooledThreadQueue;

		void uninitialize(void);
        PooledThread *createThread(void);
        PooledThread *getThread(void);

        int _initThreads;
        int _maxThreads;
        int _priority;
        PooledThreadQueue _threads;
        Mutex _threadsLock;
        bool _inited;
		volatile bool _joined;
		volatile bool _stopping;
        DISALLOW_COPY_AND_ASSIGN(ThreadPool);
    };

}

#endif // SHARED_BASE_THREADPOOL_H_
